<?php

class DebugProfilerListener extends Doctrine_EventListener
{
	public $_config='screen';

	public function prePrepare(Doctrine_Event $event)
	{
		/*
		$q = $event->getQuery();
		if(strpos($q,'agent_index') !== false) {
			trigger_error('The bad thing');
			exit;
		}
		*/
		//$this->log('Prepare',$event->getQuery());
	}

	public function preExec(Doctrine_Event $event)
	{
		$this->log('PreExecute','Query: '.$event->getQuery()."\nParams: ".print_r($event->getParams(),true));
		$event->start();
	}

	public function postExec(Doctrine_Event $event)
	{
		$event->end();
		$this->log('Execute','Elapsed Time: '.$event->getElapsedSecs());
	}

	public function preQuery(Doctrine_Event $event)
	{
		$this->log('PreQuery',$event->getQuery());
	}

	public function postQuery(Doctrine_Event $event)
	{
		$this->log('Query',print_r($event->getQuery(),true));
	}
	
	public function preStmtExecute(Doctrine_Event $event) {
		$this->log('PreStmtExecute',$event->getQuery()."\n".print_r($event->getParams(),true));
	}

	public function postStmtExecute(Doctrine_Event $event)
	{
		$this->log('PostStmtExecute','Elapsed Time: '.$event->getElapsedSecs(),$event);
	}

	private function log($type,$data,$event = false) {
		print "-$event";
		if($event) {
			$eventout = '';
			$time = 0;
			$time += $event->getElapsedSecs();
			$eventout.= $event->getName() . " " . sprintf("%f", $event->getElapsedSecs()) . "\n";
			$eventout.= $event->getQuery() . "\n";
			$params = $event->getParams();
			print "+";
			if( ! empty($params)) {
				$eventout .= print_r($params,true);
			}
		}
		if($this->_config == 'file') {
			if($f = fopen($this->_config->file,'a')) {
				if(isset($eventout)) {
					fwrite($f,$eventout);
				} else {
					fwrite($f,date('Y-m-d H:i:s')."	$type: $data\n\n");
				}
			} else {
				trigger_error('Unable to open log file for writing.');
			}
		}
		if($this->_config == 'screen') {
			if(isset($eventout)) {
				echo '<br />Doctrine_Debug: <pre>'.$eventout.'</pre>';
			} else {
				echo "\n<br />Doctrine_Debug: $type<br />\n\t<pre>$data</pre><br />\n\n";
			}
			flush();
		}
	}

}